# -*- coding:utf-8 -*-
import ctypes
import threading
import MySQLdb
import os
import socket
import json
import httplib
import urllib2
import urllib
import uuid
import zipfile
import base64
import sys
import hashlib
import datetime
import time
import subprocess
import xml.dom.minidom
import shutil
from os.path import join, getsize


def commom_log(filename, content , write_type='wb'):
    try:
        f = open(filename , write_type)
        f.write(content);
        f.close()
    except:
        print('happen an exception when write file')
        return ""

def getInfoPlist(random_filename):
    try:
        zf       = zipfile.ZipFile(random_filename, "r")
        nList    = zf.namelist()
        type_val = 0
        BundleId = ''
        CFBundleShortVersionString = ''
        CFBundleVersion = ''
        for f in nList:
            if f.rfind('Info.plist') != -1:
                f_arr = f.split("/")
                if len(f_arr) == 3:
                    if(f_arr[2] == 'Info.plist'):
                        info     = zf.read(f)
                        plist    = readPlistFromString(info)
                        BundleId = plist['CFBundleIdentifier']
                        if plist.has_key('CFBundleShortVersionString'):
                            CFBundleShortVersionString = plist['CFBundleShortVersionString']
                        else:
                            CFBundleShortVersionString = ''
                        if plist.has_key('CFBundleVersion'):
                            CFBundleVersion = plist['CFBundleVersion']
                        else:
                            CFBundleVersion = ''
        return BundleId,CFBundleShortVersionString,CFBundleVersion
    except:
        return '','',''

def get_version(random_filename):
    try:
        zf = zipfile.ZipFile(random_filename, "a")
        zf.getinfo("iTunesMetadata.plist")
        data = zf.read("iTunesMetadata.plist")
        if data :
            index   = data.rfind('bundleShortVersionString')
            if index != -1:
                index_right = data.find('</string>', index)
                version = data[index: index_right]
                version = version.replace("bundleShortVersionString</key>" , '').replace("<string>", "").strip()
            else:
                version = ''
            index   = data.rfind('bundleVersion')
            if index != -1:
                index_right = data.find('</string>', index)
                bundleVersion = data[index: index_right]
                bundleVersion = bundleVersion.replace("bundleVersion</key>" , '').replace("<string>", "").strip()
            else:
                bundleVersion = ''

            index   = data.rfind('itemId')
            if index != -1:
                index_right = data.find('</integer>', index)
                itunesid = data[index: index_right]
                itunesid = itunesid.replace("itemId</key>" , '').replace("<integer>", "").strip()
            else:
                itunesid = ''
            
            return  version,bundleVersion,itunesid
        else:
            return '','',''
    except:
        return '','',''

private_sign = "%$@#%$#%^$#%$#";

root_path = 'd:\\'
root_path = root_path.replace("\\" , "/")

rsync_path = root_path
rsync_path = rsync_path.replace(":" , "")

# src_path  = root_path+"ipas_c/"
src_path  = root_path + "ipas_c/"  # ipas_crack 破解app 输出目录
dst_path  = root_path + "ipas_bak/"    # 破解成功备份目录
signwait_dir = root_path + "ipas_d/" # 等待签名的目录
signfail_dir = root_path+'ipas_sign_failed/' # 签名失败目录
signsuc_dir  = root_path+'ipas_sign/' # 签名成功目录


post_url = 'http://admin.xyzs.com/upscript/server_j_script.php' # 修改越狱相关DB 字段

while True:

    datetime_now = datetime.datetime.now()
    datetime_now = datetime_now.strftime("%Y-%m-%d")

    listfile=os.listdir(src_path)
    if len(listfile) > 0:
        for line in listfile:
            if line.rfind('.ipa') != -1:
                print unicode( src_path+line , "GBK" ) + "======\n"
                return_value = get_version(unicode( src_path+line , "GBK" ))
                version_j = return_value[0]
                bundleVersion_j = return_value[1]
                itunesid  = return_value[2]

                if itunesid == '':
                    return_value = getInfoPlist(unicode( src_path+line , "GBK" ))

                    BundleId  = return_value[0]
                    if BundleId != '':
                        version_j = return_value[1]
                        bundleVersion_j = return_value[2]

                        conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='',port=3306,init_command="set names utf8")
                        conn.select_db('app_xyapplist')
                        cur  = conn.cursor()
                        # status 2 ： 新增 3 ： 更新
                        sql  = "select itunesid from t_xyapplist_hot where bundleid='"+str(BundleId)+"' ;";
                        cur.execute(sql)
                        result = cur.fetchone()
                        itunesid = ''
                        if result:
                            itunesid = result[0]
                        else:
                            print "itunesid not exists ===== >>> " + str(BundleId)
                            continue
                        print BundleId + " === >>" + str(itunesid) + "\n"
                        cur.close()
                        conn.close()

                if itunesid != '':

                    # copy 一份文件到 ipas_bak 目录
                    shutil.copyfile(src_path+line , dst_path + (str(itunesid))+".ipa")

                    m = hashlib.md5(str(itunesid)) 
                    m.digest()
                    md5_str = m.hexdigest()
                    str1 = md5_str[0: 2]
                    str2 = md5_str[2: 4]

                    # rsync 上传文件 到 制定目录 
                    os.system("rsync -av --port=8733 /cygdrive/"+rsync_path+"/ipas_bak/"+str(itunesid)+".ipa kingnet@192.168.12.61::data/jailbreak/"+str1+"/"+str2+"/")

                    # 这里休息 5 秒钟 , 确保rsync 同步过去 
                    time.sleep(5)

                    m = hashlib.md5(str(private_sign + (str(itunesid))))
                    m.digest()
                    sign = m.hexdigest()
                    # print "=====111=\n"
                    parameters = {'sign' : sign , 'itunesid':itunesid , 'version_j':version_j , 'bundleVersion_j':bundleVersion_j}
                    print parameters
                    data       = urllib.urlencode(parameters)
                    request    = urllib2.Request(post_url, data)
                    response   = urllib2.urlopen(request)
                    page       = response.read(200000)
                    print page # 获取返回值
                    # print "=====222=\n"

                    m = hashlib.md5(str(version_j) + str(bundleVersion_j))
                    m.digest()
                    v_params = m.hexdigest()
                    download_url = 'http://download.xyzs.com/jailbreak/'+str1+'/'+str2+'/'+str(itunesid)+'.ipa?v='+v_params
                    try:
                        print "start clear CDN :" + download_url + "\n"
                    
                        parameters = {'username' : 'xyzs' , 'password':'xyzs123' , 'type':1 , 'url':download_url}
                        data       = urllib.urlencode(parameters)
                        request    = urllib2.Request('http://pushdx.dnion.com/cdnUrlPush.do', data)
                        response   = urllib2.urlopen(request)
                        page       = response.read(200000)
                        print page
                        print "end Clear CDN \n"    
                    except:
                        print 'sleep 5 ms'
                        time.sleep(60)
                        parameters = {'username' : 'xyzs' , 'password':'xyzs123' , 'type':1 , 'url':download_url}
                        data       = urllib.urlencode(parameters)
                        request    = urllib2.Request('http://pushdx.dnion.com/cdnUrlPush.do', data)
                        response   = urllib2.urlopen(request)
                        page       = response.read(200000)
                        print page
                        print "end Clear CDN \n"  
                    
                    # copy 准备开始签名
                    shutil.move(dst_path + (str(itunesid))+".ipa" ,  signwait_dir + str(md5_str) + str2 + str1 + '_s.ipa')
                    # sign(signwait_dir)
                    print src_path+line +"------------------------"
                    os.remove(src_path+line) # 删除 原 文件

                    # commom_log('read_ipas_success_'+datetime_now+'.log' , str(itunesid) + "---" + src_path + line +  "\n" , 'a')
        else:
            print "wait 10 min ..."
            time.sleep(10)